<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport( 'joomla.application.component.model' );
jimport('joomla.filesystem.file'); 
JTable::addIncludePath(JPATH_COMPONENT.DS.'tables'); 
//require_once  JPATH_SITE.DS.'components'.DS.JBCOMNAME.DS.'models'.DS.'jafrontend_model.php';

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JobBoardModelJAProfiles extends JModel
{
    var $_table_name = 'ja_profiles';
    var $_pagination;
    var $_fieldList;
    var $_fieldListEdit;
    var $_table;
    
    /**
    * Return the query is used to retrive all row from database
    * @return string The query is used 
    */
    function getItems($where_more = '', $limit, $limitstart, $order = '') {
    	global $mainframe, $jbconfig, $option;
		
		// Get the page/component configuration
		$params = &$mainframe->getParams ();
		
		$db = JFactory::getDBO ();

		$request = JRequest::get('request');
		$filter_field_keys = array();
		if($request){
			$filter_field_keys = array_keys($request);
		}
		
		$search = "";
		if( JRequest::getVar("view") != "jajobs" && JRequest::getVar("layout") != "filter_job_list" ){
			$search = JRequest::getVar ( 'search', '' );
			$search = trim(JString::strtolower ( $search ));
		}
		
		$user = JFactory::getUser ();
		$this->getFieldList ( ' and fl.admin_only=0 ' );
		$this->getEditFieldList ( ' and f.frontend_hidden=0' );
				
		$filter_order = JRequest::getVar('filter_order', 'emplo.featured');
		$filter_order_Dir	= JRequest::getVar("filter_order_Dir",	"DESC");
		
		// just in case filter_order get's messed up
		$join = '';
		$orderby = '';
		$where = "";
		$fields_show = '';
		
		$join_clause_field = array ();
		$join_clause_table = array ();
		$field_temp = array();
		$subwhere = array ();		
		$where_clause = array();		
				
		
		$join_clause_table['emplo'] =  "\n INNER JOIN #__ja_employers as  emplo";
		$join_clause_table['rs'] =  "\n INNER JOIN #__users as rs ";
		
		$join_clause_field['emplo'] = "  ON emplo.user_id=a.user_id ";
		$join_clause_field['rs'] = " ON rs.id=a.user_id and rs.block=0";
    
    	if($search){
        	$subwhere [] .= " (rs.username LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . 
        	 					" OR rs.email LIKE " . $db->Quote ( '%' . $db->getEscaped ( $search, true ) . '%', false ) . 
        						")";
        }
        
		JB_Build_where($join_clause_table, $join_clause_field, $field_temp, $where_clause, $this->_fieldListEdit, $filter_field_keys, $request, $search, $subwhere);			
		
		if ($order) {
			$orderby .= $order;
		}
		if ($filter_order) {			
			if ($orderby)	$orderby .= ',';
			$orderby .= $filter_order . ' ' . $filter_order_Dir ;
		
		} elseif (! $order) {
			$orderby = " a.id";
		}
		
		if($field_temp){
			$fields_show = ', '. implode(', ', $field_temp);	
		}
		
		foreach ($join_clause_table as $j=>$table){
			$join .= "\n $table ";
			if(isset($join_clause_field[$j])){
				$join .= $join_clause_field[$j];
			}
		}
			
		if ($where_clause) {
			$where = ' AND ' .implode(' AND ', $where_clause);
		}
			
		/* Count items */
		$query = "SELECT count(distinct a.id) ".
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more;	
		
		$db->setQuery ( $query );//echo $db->getQuery();exit;
		$total = $db->loadResult ();
		
		jimport ( 'joomla.html.pagination' );
		$this->_pagination = new JPagination ( $total, $limitstart, $limit );
		
		/* Get all items */
		$query = "SELECT distinct a.id, a.*, emplo.featured $fields_show" . 
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more.
					"\n ORDER BY ". $orderby . ', a.id desc';
		
		$db->setQuery ( $query, $limitstart, $limit );//echo $db->getQuery();exit;
		
		$items = $db->loadObjectList ();
						
		if ($items) {
			foreach ( $items as $k => $job ) {
				if (isset($job->id)){					
					
					$job->short_desc = JFilterInput::_decode($job->short_desc);
					
					if ($this->_fieldList) {
							foreach ( $this->_fieldList as $field ) {
								
								$job->{$field->field_name} = JFilterInput::_decode ( $job->{$field->field_name} );
									
								if ($field->field_type == 'TEXTFIELD'){
									$job->{$field->field_name} = JFilterInput::clean ( $job->{$field->field_name} );
								}							
	
								
								if ($field->is_referred > 0 && $job->{$field->field_name}) {
									
									
									$values = explode(',', $job->{$field->field_name});
									foreach ($values as $i=>$v){
										$values[$i] = $db->Quote($v);	
									}
									$values = implode(',', $values);
									if(!$values) $values = 0;
									
									$sql = "SELECT {$field->referred_value} ".
											"\n FROM #__{$field->referred_table} ".
											"\n WHERE {$field->referred_key} in ($values)";
									$db->setQuery ( $sql );
									$result = $db->loadResultArray ();
									if ($result) {
										$job->{$field->field_name} = implode(', ', $result);
									}
									else{
										$job->{$field->field_name} = '';
									}
									
									
								} elseif (in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) ) && $job->{$field->field_name}) {
									
									$values = explode(',', $job->{$field->field_name});
									foreach ($values as $i=>$v){
										$values[$i] = $db->Quote($v);	
									}
									$values = implode(',', $values);
									$field_id = $field->table_name . '_' . $field->field_name;
									
									$sql = "SELECT text ".
											"\n FROM #__ja_codes ".
											"\n WHERE value in ($values) and field_id='$field_id' ";
																	
									$db->setQuery ( $sql );
									$result = $db->loadResultArray ();
									
									if ($result) {
										$job->{$field->field_name} = implode(', ', $result);
									}
									else{
										$job->{$field->field_name} = '';
									}
								}
						}
						
						$items [$k] = $job;
					}
					
					
				}
			}
		}
		
		return $items;
	
	}
	
    
    
    /**
    * @desc Get all fields that will be displayed on edit form
    */
    function getEditFieldList($where = ''){        
        if(!$this->_fieldListEdit){
	        $this->_fieldListEdit = getEditFieldList($this->_table_name);
        }   
		return $this->_fieldListEdit ;       
    }
    
    function getFieldList($where=''){
    	if(!$this->_fieldList){
    		$this->_fieldList = getFieldList($this->_table_name, $where); 
    	}
    	
    	return  $this->_fieldList;
    }
    
    /**
    * Get field table instance
    * @return JTable Configuration table object
    */
    function &_getTable(){
        if($this->_table == null){
        	$this->_table = &JTable::getInstance('JA_Profiles', 'JobBoardTable');
        }
		return $this->_table;
	}
	
	/**
	* Get page navigator object
	* @return 
	*/
	function &getPagination(){
		if ($this->_pagination == null) {
			$this->getItems();
		}
		return $this->_pagination;
	}
	
	/**
	* Get configuration item
	* @return JobboardTableJA_resumes Table object
	*/
	function getItem($user_id=0){
		static $item;
		if (isset($item)) {
			return $item;
		}				
		$user = JFactory::getUser($user_id);			
		if(!$user->id || $user->block){
			$user_id = 0;
		}	
		
		$table = $this->_getTable();
        
		if ($user_id && (JRequest::getVar('userdetail')==null) ) {
			$table->_tbl_key = 'user_id';
			$table->load((int)$user_id);
		}		
		if (JRequest::getVar('view')=='jausergroup'){
			$user = JFactory::getUser();	
			$table->load($user->id);
		}
	    return $table;	    
	}
    
	/** 
	* Store configuration item
	* @param array The post array
	*/
	function store( $needCheck = true ){
	    // Initialize variables
	    global $jbconfig;
	    $controller = 'japrofiles';
	    $user = & JFactory::getUser();
		$db		=& JFactory::getDBO();
		$row	=& $this->getItem($user->id);
		$row->_tbl_key = 'id';
		if ($row->id == null || $row->id==0)
		{
			$newprofile = 1;
			$row->approved = $jbconfig['account']->get('em_needs_approved')==1?0:1;
		}
		else 
			$newprofile = 0;
		$post    = JRequest::get('request', JREQUEST_ALLOWRAW);
		if(!isset($post['user_id']) || !$post['user_id']){
			$post['user_id'] = $user->id;			
		}
		if (!$row->created_date)
			$post['created_date'] = date("Y-m-d H:i:s");
		
		foreach ($post as $k=>$value){
			if($k!='cid' && is_array($value)){
				$post[$k] = implode(',', $value);
			}
			elseif(!is_array ( $value )){
				$post [$k] = trim($value);
			}
		}
		
		$step = JRequest::getVar('step', '');
        if($step != 'done')
        {  
        	if (!$row->bind( $post )) 
        	{
			    return false;
		    }
		    
           if( $needCheck ){
	            if ($row->spec_field)
	            {
	            	if (!assign_spec_field($controller,$row))
	            		return false; 
	            }
	 			
	            if ($row->editor_field)
					assign_editor_field($row);
	            
			    if (!$this->checkData($row))
			    {
				    return false;
			    }
		    }
		    
			if (!$row->store())
		    {
			    return false;
		    }		   		
        } 
		
		return $row->id;
	}
    
	function checkData()
	{
		// Initialize variables
	    global $jbconfig;
	    $controller = 'japrofiles';
	    $user = & JFactory::getUser();
		$db		=& JFactory::getDBO();
		$row	=& $this->getItem($user->id);
		
		$row->_tbl_key = 'id';
		
		$post    = JRequest::get('request', JREQUEST_ALLOWRAW);
		
		if(!isset($post['user_id']) || !$post['user_id']){
			$post['user_id'] = $user->id;			
		}
		if (!$row->created_date)
			$post['created_date'] = date("Y-m-d H:i:s");
		
		foreach ($post as $k=>$value){
			if($k!='cid' && is_array($value)){
				$post[$k] = implode(',', $value);
			}
		}
		
		if (!$row->bind( $post )) 
    	{
		    return false;
	    }
	    
	    if ($row->id == null || $row->id==0)
		{
			$row->approved = $jbconfig['account']->get('em_needs_approved')==1?0:1;
		}
	    
        if ($row->spec_field)
        {
        	if (!assign_spec_field($controller,$row))
        		return false; 
        }
			
        if ($row->editor_field)
			assign_editor_field($row);
        
	    if (!$row->check())
	    {
		    return false;
	    }
		return $row;
	}
	
    /**
    * Approve/Unapprove the resumes 
    * 
    */
    function approved($task = 'approved'){
        global $mainframe;
        $cid = JRequest::getVar('cid',array(), 'post', 'array');
        $n =  count($cid);
        JArrayHelper::toInteger( $cid );
        
        $table_name        = "ja_profiles";
        $is_approved = ($task == 'approved') ? 1 : 0;
        
        if($table_name){
            
            $query = "UPDATE #__$table_name SET is_approved = $is_approved WHERE id = ". implode(" OR id = ", $cid);
            $db = &JFactory::getDBO();
            $db->setQuery($query);

            return $db->query();
        }
        return false;
    }
    
    /**
    * Publish/Unpublish the resumes
    * 
    */
    function published($task = 'published'){
        $cid = JRequest::getVar('cid',array(), 'post', 'array');
        $n =  count($cid);
        JArrayHelper::toInteger( $cid );
        
        $is_published = $task == 'published' ? 1 : 0;
        
        $query = "UPDATE #__ja_resumes SET is_published = $is_published WHERE id = ". implode(" OR id = ", $cid);
        $db = &JFactory::getDBO();
        $db->setQuery($query);
        
        return $db->query();
    }
    
    /**
    * Publish/Unpublish the resumes
    * 
    */
    function activate($task){
        
        $cid = JRequest::getVar('cid', array(), 'post', 'array');
        $field = JRequest::getVar('field', "", 'post', 'cmd');
        $table_name = JRequest::getVar('table_name',"", 'post', 'cmd');
        $n =  count($cid);
        JArrayHelper::toInteger( $cid );
        
        $active =  $task == "activate" ? 1 : 0;
        
        if($field == "is_starred"){
            
            $shortlistmd = JController::_createModel(JBPREFIX."ShortList", "JobBoardModel");
            $shortlistmd->starred($task == "activate" ? "starred" : "unstarred");
        } else if($table_name && $field){
            $query = "UPDATE #__$table_name SET $field = $active WHERE id = ". implode(" OR id = ", $cid);
            
            $db = &JFactory::getDBO();
            $db->setQuery($query);
            
            return $db->query();
        }
        return false;
    }
    
    function increaseViews(){
        $item = $this->getItem();
        $item->views++;
        return $this->store();
    }
    
    /**
    * Remove field record
    * @return Number of removed records
    */
    function remove($task = 'remove'){
        $cid = JRequest::getVar('cid',array(), 'post', 'array');
        $n =  count($cid);
        JArrayHelper::toInteger( $cid );
        
        if($n){
            if($task == 'remove'){
                $query = "DELETE FROM #__ja_profiles WHERE id = ". implode(" OR id = ", $cid);
                
                $db = &JFactory::getDBO();
                $db->setQuery($query);
                if($db->query()){
                    return $n;
                }
            }
        }
        
        return 0;
    }
    
    function EmployerMailSignUp($profile_id, $user, $emailtemplate = 'EmployerMailSignUp')
    {
    	global $jbconfig;
    	$arr_link = array();
    	$arr_link['ja_profiles'] = $profile_id;
    	$arr_link['users'] = $user->id;
    	$emailConfig = JobBoardConstant::getEmailConfig();
    	$mail = get_EmailTemplate($arr_link, $emailtemplate);
    	
    	if ($mail)
    	{
    		if (!$mail->EmailFromAddress) 
    			$mail->EmailFromAddress = $emailConfig['fromemail'];
    		if (!$mail->EmailFromName) 
    			$mail->EmailFromName = $emailConfig['fromname'];	
    		return sendMail($user->email,$user->name,$mail->subject,$mail->content,'',$mail->EmailFromAddress, $mail->EmailFromName);
    	}
    	else 
    	{
    		JError::raiseWarning(0,JText::_('Email template system was not found! Please contact to Administrator!'));
    		return false;
    	}
    }    
    
    function download(){
        $cid = JRequest::getVar('cid',array(), 'post', 'array');
        $n =  count($cid);
        JArrayHelper::toInteger( $cid );
        
        $item = $this->getItem();
        $file_name = explode('/',$item->attachment);
        if( $item->attachment) {
            $file = JPATH_SITE.DS.$item->attachment;
            if (file_exists(str_replace('/','\\',$file)))
	        	$file = str_replace('/','\\',$file);
	        else 
	        	$file = str_replace('\\','/',$file);
            
	        if ( ! file_exists($file) ){
        		echo JText::_("<script language='javascript'> alert('".JText::_("File not found on the Server")."'); </script>");
        		return ;
        	}
        	
            header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename="'.substr ( $file_name [count ( $file_name ) - 1], 14 ) .'"');
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
		    ob_clean();
		    flush();
		    readfile($file);
        }
    }
    
    function remove_attach()
    {
    	remove_attach('ja_profiles');

    }
    
}
?>